import Vue from "vue";
import Router from "vue-router";
import routes from "./routes";
import config from "@/config";
import storage from "@/libs/storage";
import {logout, modifySignStatus} from "@/libs/index";

Vue.use(Router);

const router = new Router({
    mode: "history",
    base: process.env.VUE_APP_BASEPATH,
    routes,
});

// no redirect whitelist
const whiteList = ["/login", "/privacy", "/protocol", "/order", "/register", "/changepass"];

router.beforeEach(async (to, from, next) => {
    const now = new Date().getTime();
    const token = storage.get("token");
    Vue.prototype.$Progress.start();
    if (storage.get("token") && storage.get("time") && now - storage.get("time") < 1000 * 60 * 60 * 2) {
        // 删除官网目标网址信息
        storage.delete("entryType");
        modifySignStatus(token, storage.get("userInfo"));
        /* has token and validate*/
        next();
    } else {
        /* has no token or not validate*/
        modifySignStatus("", null);
        logout();
        const isWhite = whiteList.some((item) => {
            return to.fullPath.indexOf(item) !== -1;
        });
        if (isWhite) {
            // 在免登录白名单，直接进入
            next();
        } else {
            next(`/login?redirect=${to.path}`); // 否则全部重定向到登录页
        }
    }
});

router.afterEach((to, from) => {
    document.title = to.meta.title || config.title;
    router.app.$nextTick(() => {
        const container = document.querySelector(".admin");
        if (container) {
            container.scrollTo({top: 0});
        }
    });
    Vue.prototype.$Progress.finish();
});

export default router;
